//
//  XCNetworkingTool.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/2/27.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit
import AFNetworking

class XCNetworkingTool: NSObject {
   /// 定义了 AFHTTPSessionManager 的属性
    let afnManager: AFHTTPSessionManager
    
/// 创建了一个单例对象
   static let sharedInstance:XCNetworkingTool = XCNetworkingTool()
    // private表示私有方法,除这个文件外的其它类是不知道这个方法的
    private  override  init() {
        let baseUrlStr = NSURL(string: "https://api.weibo.com/")
        
        afnManager = AFHTTPSessionManager(baseURL: baseUrlStr)
        /*=====================请求的超时长，默认是60秒==============================*/
        afnManager.requestSerializer.timeoutInterval = 20
         afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    // MARK: - Oauth授权相关
    let client_id = "2627806802"                            //    App Key
    let client_secret = "c8cdacad7f5a99376754871e72dd18a6"  //    App Secret
    ///   回调地址
    let redirect_uri = "http://www.baidu.com/"
    /// 请求授权的url
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    /// 返回授权的URL
    func oauthLoginUrl() ->NSURL {
        let urlStr = oauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
   //     https://api.weibo.com/oauth2/authorize?client_id=2627806802&redirect_uri=http://www.baidu.com/
        return NSURL(string: urlStr)!
    }
    
    // 获取AccessToken[     /// 定义了一个完成回调的闭包
    func loadAccessToken(code:String ,AccessTokenFinised: (resposed:[String : AnyObject]? , error:NSError?) ->()){
    // 3.3.请求地址
     let url = "https://api.weibo.com/oauth2/access_token"
    // 3.4.请求参数
        let parameters = [
            "client_id" : client_id, //申请应用时分配的AppKey。
            "client_secret" : client_secret,//申请应用时分配的AppSecret。
            "grant_type" : "authorization_code",//请求的类型，填写authorization_code
            "code" : code,  //	调用authorize获得的code值。
            "redirect_uri" : redirect_uri //回调地址，需需与注册应用里的回调地址一致
        ]

    // 3.5发送POST请求
        afnManager.POST(url, parameters: parameters, progress: nil, success: { (_, responsed) -> Void in
            ///
            let dict = responsed as? [String : AnyObject]
     // 3.6获取到数据,调用闭包
            AccessTokenFinised(resposed: dict, error: nil)
            

            
            }) { (_, error) -> Void in
                print("XCNetworkingTool Access_Token 请求失败 ：\(error)")
                AccessTokenFinised(resposed: nil, error: error);
        }
    }
    
    
    
    
   /// MARK: -发送请求用户数据

    let uid = XCUSerAccountViewModel.sharedInstance.userAccount?.uid
    
    
    func loadUserStatus(FinisedCallBack:(result:[String : AnyObject]?,error:NSError?) ->()){
    // 判断access_token 有值就拆包 没值就执行 access_token 没有值
//    guard let AccessToken = XCUSerAccountViewModel.sharedInstance.userAccount?.access_token  else{
//            print(" access_token 没有值")
//            return
//        }
        // 判断uid 有值就拆包 没值就执行 uid 没有值
        guard let uid = XCUSerAccountViewModel.sharedInstance.userAccount?.uid else {
        print("uid 没有值 ")
            return
        }
        
        let urlStr = "https://api.weibo.com/2/users/show.json"

        let parameters = ["uid" : uid]
     
        requestGET(urlStr, paramters: parameters) { (result, error) -> () in
        FinisedCallBack(result: result, error: error)
        }
        

    }

   

//=====================================================================================
    
//=====================================================================================
    
//=====================================================================================
     // MARK：- 加载微博数据
    func loadStatus( since_id: Int, max_id: Int, finished:(result:[String : AnyObject]?,error:NSError?) ->()){
            // 判断access_token 有值就拆包 没值就执行 access_token 没有值
//            guard let accessToken = XCUSerAccountViewModel.sharedInstance.userAccount?.access_token  else{
//                print(" access_token 没有值")
//                return
//            }
        
        let deBug = true
        
        if deBug {
            loadLocalStatus({ (result, error) -> () in
                finished(result: result, error: nil)
            })
            return
        }
        
        
            let Url = "https://api.weibo.com/2/statuses/home_timeline.json"
//            let paramters = ["access_token" : accessToken]
//        https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00O1SiwCgaAqrC16215fa3ddeyBXNC
        
        // 添加请求参数
        var parameters = [String: AnyObject]()
        // 别人传递  since_id
        if since_id > 0{
            parameters["since_id"] = since_id
        }else if max_id > 0{
            parameters["max_id"] = max_id - 1
        }
        
//        requestGET(Url, paramters: parameters) { (result, error) -> () in
//            finished(result: result, error: error)
//        }
        
        requestGET(Url, paramters: parameters, finished: finished)

      
        }
    
    /// 加载本地数据
    func loadLocalStatus(finished:(result:[String : AnyObject]?,error:NSError?) ->()){
        let LocalPath = NSBundle.mainBundle().pathForResource("statuseses", ofType: "json")!
        print("LocalPath = \(LocalPath)")
       
        let data = NSData(contentsOfFile: LocalPath)!
        
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
            
            finished(result: json as? [String:AnyObject], error: nil)
            
        }catch{
            
        }
        
    }
    
    
    
    
    // MARK: - 封装 GET 请求
    func requestGET(urlStr:String,var paramters:[String:AnyObject]?,finished:(result: [String: AnyObject]?, error: NSError?) ->()){
        
        // 判断access_token 有值就拆包 没值就执行 access_token 没有值
        guard let accessToken = XCUSerAccountViewModel.sharedInstance.userAccount?.access_token  else{
           
            finished(result: nil, error: nil)  // 新添加的代码
            print(" access_token 没有值")
            return
        }
        if paramters == nil{
            paramters = [String: AnyObject]()
        }
        paramters!["access_token"] = accessToken
        
        afnManager.GET(urlStr, parameters: paramters, progress: nil, success: { (_, result) -> Void in
            // 从服务器获取得到的 result 要是没装换成 result as? [String : AnyObject] 就直接报错

            finished(result: result as? [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    

}














